
//评论框键盘收起

var commitBoxState = false;//false 表示未聚焦 true表示唤醒

function packupKeyboard() {
    if (commitBoxState == true){
        commitBoxState = false;
        $('.comment_box_text').blur();
        //$('.down_navbar_div').focus();
        $('.bottom_comment_box').css('bottom','0');
    }
    //$('.bottom_comment_box').css('bottom','0');
    //$('.comment_box_real').blur();
}

//function keyboardShow(height){
//    $('.bottom_comment_box').css('bottom',height + "px");
//}


$(function(){


    //设置全局变量
    //-----跳转到已读的页面  需要的信息
    var log_detail_title_jump       = "";
    var _name                       = [];
    var _cover                      = [];
    var _id                         = [];
    var _qyxBindId_arr              = [];
    var dailyrecord_temp_id         = "";

    var _token;
    var _userId;
    var _imToken;
    var _qyxBindId;
    var _group_id;

    var _userName;
    var _logName;
    //获取url的参数
    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);
    var index           = $.getUrlParam('index');               //判断弹框
    var dailyrecord_id  = $.getUrlParam('id');                  //获取 日志id

    var token           = $.getUrlParam('token');               //获取分享过来的 token;
    var userId          = $.getUrlParam('userId');              //用户id
    var imToken         = $.getUrlParam('imToken');
    var qyxBindId       = $.getUrlParam('qyxBindId');
    var group_id        = $.getUrlParam('teamId');
    if(index==undefined){
        index  = "2";
    }
    if(token==undefined||token==null){
        _token = localStorage.token;
        _userId = localStorage.user_id;
        _imToken = localStorage.imToken;
        _qyxBindId = localStorage.qyxBindId;
        _group_id = localStorage.group_id;
    }else{
        _token = token;
        _userId = userId;
        _imToken = imToken;
        _qyxBindId = qyxBindId;
        _group_id = group_id;
    }
    //var user_id = $.getUrlParam('user_id');         //获取 日志阅读人id
    if(index=="1"||index=="2"){
        $(".title_up").html("分享");
    }else{
        $(".title_up").html("修改日志");
    }

    //点击打开遮盖
    $(".btn_choice").on('click',function(){
        $(".decide_delete").hide();
        $(".big_img").remove();
        $(".call_back").fadeIn(150,function(){
            $(".content_big").fadeIn(100);
        });
    });
    //点击"取消",关闭遮盖
    $(".title_down").on('click',function(){
        $(".call_back").fadeOut(150);
    });
    //点击"删除",弹出删除框
    $(".title_mid").on('click',function(){

        if (event.stopPropagation()){
            event.stopPropagation();
        }else{
            event.cancelBubble = true;
        }

        $(".content_big").hide();
        $(".decide_delete").fadeIn(150);
    });

    //点击"取消","确认"
    $("#cancel").on('click',function(){
        $(".call_back").fadeOut(150);
    });

    //点击空白处
    $(".call_back").on('click',function(){
        $(".call_back").fadeOut(150);
    });
    $("#sure").on('click',function(){
        $(".call_back").hide();
        var data = {
            userId:_userId,
            token:_token,
            imtoken:_imToken,
            qyxBindId:_qyxBindId,
            title:_userName+"的"+_logName+"已被删除"
        };
        //发送ajax请求
        $.ajax({
            beforeSend:function(){
                $('.call_back_success').html('正在删除...').show();
            },
            //url:apiurl+"/dailyrecords/"+dailyrecord_id+"?userId="+_userId+"&token="+_token+"&imtoken="+_imToken+"&qyxBindId="+_qyxBindId+"&title="+_userName+"的"+_logName+"已被删除"+"",
            url:apiurl+"/dailyrecords/"+dailyrecord_id+"/delete",
            type:"POST",
            data:data,
            success:function(d){
                if(typeof d == "object"){
                    var msg= d.msg;
                    if(msg=="202") {
                        $(".token_iframe").fadeIn(1000);
                    }
                }else{
                    var data = JSON.parse(d);
                    if(data.code=="0"){
                        $(".call_back_success").hide().html("删除成功").show();
                    }else{
                        $(".call_back_success").html(data.msg);
                    }
                    $(".call_back_success").fadeIn(1000,function(){
                        //debugger;
                        //var localstorage = window.localStorage;
                        //localstorage.setItem("dailyrecordDeleteFlag","true");

                        window.location.href = "allLog.html?index=1";
                    });
                }
            }
        });
    });
    //点击 修改日志 跳转到showLogModel页面
    $(document).on('click','.title_up',function(){

        if (event.stopPropagation()){
            event.stopPropagation();
        }else{
            event.cancelBubble = true;
        }

        if($(this).html()=="修改日志"){
            window.location.href="showLogModel.html?dailyrecord_id="+dailyrecord_id+"&edit=edit&id="+dailyrecord_temp_id+"";
        }
        if($(this).html()=="分享"){
            var attId           ="";
            var team            =_group_id;
            var content         ="日志分享";
            var title           ="";
            var applicationId   =dailyrecord_id;
            var applicationType =6;
            var attSize         ="";
            var hyperlink       ="/log/logHtml/logDetail.html?id="+dailyrecord_id+"";

            shareContent(attId,team,content,title,applicationId,applicationType,attSize,hyperlink);
        }
    });

    //点击跳转"已读人员"
    $(document).on('click',".had_read_person_num",function(){
        window.location.href    = "logRead.html?title="+log_detail_title_jump+"&id="+dailyrecord_id;
        localStorage.name       = _name;
        localStorage.id         = _id;
        localStorage.avatar     = _cover;
        localStorage.qyxBindId_log  = _qyxBindId_arr;
    });


    //获取网络数据
    $.ajax({
        beforeSend:function(){
            $(".loading").show();
            $(".show_hide").hide();
        },
        url:apiurl+"/dailyrecords/"+dailyrecord_id+"",
        type:"GET",
        data:{
            user_id:_userId,
            token:_token
        },
        success:function(d){
            if(typeof d == "object"){
                var msg= d.msg;
                if(msg=="202") {
                    $(".token_iframe").fadeIn(1000);
                }
            }
            else
            {
                $(".loading").hide();

                var data        = JSON.parse(d).data;


                //debugger;

                var userInfo    = data.userCallbackString;

                var user_id                 = data.user_id;                                  //获取user_id
                var user_name;
                var user_qyxBindId;
                var user_icon;
                for(var u in userInfo){
                    if(userInfo[u].id==user_id){
                        _userName = user_name   = userInfo[u].name;
                        user_qyxBindId          = userInfo[u].qyxBindId;
                        user_icon               = userInfo[u].avatar;
                    }
                }


                //非自己发布 隐藏删除
                if (user_id != _userId){
                    $("#option_delete").hide();
                    $(".content_big").attr("style","height:15.4375vh");
                }

                var avatar_img;
                //if(user_icon=="") {
                    var color = avatar_getColor(user_qyxBindId);
                    avatar_img = "<div class='me_cover_div' style='background-color: "+color+"'>"+avatar_name(user_name)+"</div>"
                //}else{
                if (user_icon.length > 0) {
                    var src = avatar_getUrl(_userId,_token,user_icon);
                    avatar_img += "<img class='me_cover' src='"+src+"' hidden>";
                }
                var is_comment              = data.is_comment;                               //获取是否已经评论
                var create_timestamp        = data.create_timestamp;                         //获取日志创建时间
                var dailyrecordTemp         = data.dailyrecordTemp;                          //获取日志模板 包括值
                var dailyrecord_img         = data.dailyrecord_img;                          //获取日志填写时上传的图片
                var follows                 =data.followerRelations;                                   //获取抄送人
                var dailyrecord_temp_title  =dailyrecordTemp.dailyrecord_temp_title;         //获取 日志模板名称
                _logName                    = dailyrecord_temp_title;
                var fieldValues             = dailyrecordTemp.fieldValues;                   //获取 日志模板填写的值
                dailyrecord_temp_id         = data.dailyrecord_temp_id;                      //获取 日志模板id  用于修改日志
                log_detail_title_jump       = escape(dailyrecord_temp_title);                //将 日志模板名称编码  传给  已读 页面


                var date = new Date(create_timestamp);
                initDate(date);
                //详情页title为模板的名称
                $(".title").html(dailyrecord_temp_title);
                //是否已经评论
                var comment_img_html="";
                if(is_comment=="0"){
                    comment_img_html = "<div id='watermark'></div>";
                    $("#watermark").show();
                    $("#watermark_had").hide();
                }else{
                    comment_img_html = "<div id='watermark_had'></div>";
                }
                if(_userId==user_id){
                    comment_img_html = "";
                }
                //加载信息
                //-------加载 日志发起人 信息
                var user_detail_html = "<div style='width: 100%;height: auto;'><div class='first_div_me_big'><div class='col-xs-3'>"+avatar_img+"</div><div class='col-xs-9'><div class='name_div'>"+user_name+"</div><div class='name_time'>"+year_min+"</div></div><div style='clear: both'></div></div>"+comment_img_html+"</div>";

                //-------加载模板信息
                var model_html = "";
                for(var i=0;i<fieldValues.length;i++){
                    //文本型 数字型 下拉选择项 日期型
                    var daiyrecord_temp_field_type = fieldValues[i].daiyrecord_temp_field_type;      //类型
                    var dailyrecord_temp_field_title = fieldValues[i].dailyrecord_temp_field_title;  //字段标题
                    var default_value = fieldValues[i].default_value;                                //字段的值
                    //var options = fieldValues[i].options;                                          //选择项
                    var html="";
                    var time;
                    if(daiyrecord_temp_field_type=="0"){
                        var val_arr  = default_value.split("\n");
                        var val_html ="";
                        for(val in val_arr){
                            val_html += "<div class='note_val'>"+val_arr[val]+"</div>"
                        }

                        var style = "";
                        if (dailyrecord_temp_field_title == "备注"  && dailyrecord_img.length == 0){
                            style = "border:none";
                        }

                        html = "<div class='detail_content_big'><div style='" + style + "' class='detail_content_mid'><div class='detail_title'>"+dailyrecord_temp_field_title+"</div><div class='detail_real_do'>"+val_html+"</div></div></div>";
                    }else if(daiyrecord_temp_field_type=="3"){
                        if(default_value!=""){
                            var date1 = new Date(Math.round(default_value));
                            initDate(date1);
                            time = year_whole;
                        }else{
                            time = "";
                        }
                        html = "<div class='detail_content_big'><div class='detail_content_mid'><div class='detail_title'>"+dailyrecord_temp_field_title+"</div><div class='detail_real_do'>"+time+"</div></div></div>";
                    }else if(daiyrecord_temp_field_type=="4"){
                        if(default_value!=""){
                            var date2 = new Date(Math.round(default_value));
                            initDate(date2);
                            time = year_mon_day;
                        }else{
                            time = "";
                        }
                        html = "<div class='detail_content_big'><div class='detail_content_mid'><div class='detail_title'>"+dailyrecord_temp_field_title+"</div><div class='detail_real_do'>"+time+"</div></div></div>";
                    }else{
                        html = "<div class='detail_content_big'><div class='detail_content_mid'><div class='detail_title'>"+dailyrecord_temp_field_title+"</div><div class='detail_real_do'>"+default_value+"</div></div></div>";
                    }
                    model_html += html;
                }

                //添加图片
                var img_arr = dailyrecord_img.split(",");
                var img_html = "";
                var img_html_big;
                if(img_arr!=""){
                    for(var j=0;j<img_arr.length;j++){
                        img_html += "<img src='"+img_arr[j]+"' class='img_img'>";
                    }
                    img_html_big = "<div class='img_big'><div class='img_mid'><div class='img_text'>附件:</div><div class='img_content'>"+img_html+"</div></div></div>";
                }else{
                    img_html_big="";
                }
                //添加 已读
                //console.log(follows);
                var follow_arr = [];
                if(follows.length>0){
                    for(var fo=0;fo<follows.length;fo++){
                        var is_read = follows[fo].is_read;
                        if(is_read=="1"){
                            follow_arr.push(follows[fo].user_id);
                        }
                    }
                }
                var num_person = 0;
                var had_read_person_html = "";
                var had_read_html;
                if(follow_arr!=""){

                    for(var f=follow_arr.length - 1;f>=0;f--){
                        var name        ="";
                        var userId      ="";
                        var avatar      ="";
                        var qyxBindId   ="";
                        for(var b=0;b<userInfo.length;b++){
                            if(userInfo[b].id==follow_arr[f]){
                                name    = userInfo[b].name;
                                userId  = userInfo[b].id;
                                avatar  = userInfo[b].avatar;
                                qyxBindId= userInfo[b].qyxBindId;
                            }
                        }
                        var avatar_img2;
                        //if(avatar=="") {
                            var color2 = avatar_getColor(qyxBindId);
                            avatar_img2 = "<div class='had_read_person_head_div' style='background-color: "+color2+"'>"+avatar_name(name)+"</div>"
                        //}else{
                        if (avatar.length > 0) {
                            var src2 = avatar_getUrl(_userId,_token,avatar);
                            avatar_img2 += "<img src='"+src2+"' class='had_read_person_head' hidden>";
                        }
                        _name.push(name);
                        _id.push(userId);
                        _cover.push(avatar);
                        _qyxBindId_arr.push(qyxBindId);
                        num_person +=1;
                        had_read_person_html += "<div class='had_read_person_big'>"+avatar_img2+"<div class='had_read_person_name'>"+name+"</div></div>";
                    }
                    had_read_html = "<div class='had_read_big'>" +
                        "<div class='had_read_up'><div class='col-xs-3 had_read_text'>已读</div><div class='col-xs-6 blank'></div><div class='col-xs-3 had_read_person_num'>("+num_person+"人)<img src='../logImg/rightIcon.png' class='right_icon'></div></div> " +
                        "<div class='had_read_down'>"+had_read_person_html+"</div></div>";
                }else{
                    had_read_html = "<div class='had_read_big'>" +
                        "<div class='had_read_up'><div class='col-xs-3 had_read_text'>已读</div><div class='col-xs-6 blank'></div><div class='col-xs-3 had_read_person_num'>(0人)<img src='../logImg/rightIcon.png' class='right_icon'></div></div> " +
                        "</div>";
                }

                $(".show_hide").show();
                $(".model_detail").append(user_detail_html+model_html+img_html_big+had_read_html);


                //样式调整
                $(".had_read_person_head").each(function(){
                    var parent = $(this).parent();
                    var parentWidth = parent.width();
                    var currentWidth = $(this).width();

                    var marginLeft = (parentWidth - currentWidth)/2;

                    $(this).css("margin-left",marginLeft + "px");
                });

                showAvatar(".me_cover");
                showAvatar(".had_read_person_head");
            }
        }
    });

    //获取 评论
    //评论
    var comment_html = "";
    var comment_html_num = "";
    var comment_html_real = "";

    $.ajax({
        url:apiurl+"/dailyrecords/"+dailyrecord_id+"/comment/list",
        type:"GET",
        data:{
            user_id:_userId,
            token:_token
        },
        success:function(d){
            if(typeof d == "object"){
                var msg= d.msg;
                if(msg=="202") {
                    $(".token_iframe").fadeIn(1000);
                }
            }
            else
            {
                var data        = JSON.parse(d).data.list;
                var userInfo    = JSON.parse(d).data.userCallbackString;

                //console.log(dailyrecord_id);
                //console.log(data);
                var num_person = 0;
                if(data==""){
                    comment_html = "<div class='comment_blank'>暂无评论...</div>";
                }else{
                    for(var i=0;i<data.length;i++){
                        var comment_body    = data[i].comment_body;
                        var user_id         = data[i].user_id;
                        var timestamp       = data[i].timestamp;
                        var name;
                        var avatar;
                        var qyxBindId;
                        for(var j=0;j<userInfo.length;j++){
                            if(userInfo[j].id==user_id){
                                name        = userInfo[j].name;
                                avatar      = userInfo[j].avatar;
                                qyxBindId   = userInfo[j].qyxBindId;
                            }
                        }
                        var avatar_img;
                        //if(avatar=="") {
                            var color = avatar_getColor(qyxBindId);
                            avatar_img = "<div class='comment_cover_img_div' style='background-color: "+color+"'>"+avatar_name(name)+"</div>"
                        //}else{
                        if (avatar.length > 0) {
                            var src = avatar_getUrl(_userId,_token,avatar);
                            avatar_img += "<img src='"+src+"' class='comment_cover_img' hidden>";
                        }
                        var date = new Date(timestamp);
                        initDate(date);
                        num_person++;

                        //var arr = value.split('\n');
                        //var html_single = "";
                        //for(key in arr){
                        //    html_single += "<div class='real_content'>"+arr[key]+"</div>";
                        //}
                        var arr = comment_body.split('\n');
                        var html_single = "";
                        for(key in arr){
                            html_single += "<div class='comment_content_real_div_down_real'>"+arr[key]+"</div>";
                        }

                        comment_html_real +=
                            "<div class='comment_content_big'>" +
                                "<div class='comment_cover_div col-xs-2'>"+avatar_img+"</div>" +
                                "<div class='comment_content_real_div col-xs-10'>" +
                                    "<div class='comment_content_real_div_up'>" +
                                        "<div class='col-xs-6 comment_content_real_div_up_name'>"+name+"</div>" +
                                        "<div class='col-xs-6 comment_content_real_div_up_time' style='text-align: right'>"+day_min+"</div>" +
                                    "</div>" +
                                    "<div class='comment_content_real_div_down'>" +
                                        html_single +
                                    "</div>" +
                                "</div>" +
                            "</div>";

                    }
                    comment_html = "<div class='comment_up_div'>共"+num_person+"条回复</div><div class='comment_down_div'>"+comment_html_real+"</div>";
                }

                var comment_content_html = "<div class='comment_big'>"+comment_html+"</div>";
                $(".show_hide").append(comment_content_html);
                $(".comment_content_real_div").last().css("borderBottom","none");

                showAvatar(".comment_cover_img");
            }
        }
    });


    //发送评论
    $(".send_btn").on('click',function(){

        packupKeyboard();
        var body = $(".comment_box_text").html();

        //debugger;
        if (body.length > 0) {
            var data={
                user_id:_userId,
                comment_body:body,
                token:_token,
                imtoken:_imToken,
                qyxBindId:_qyxBindId,
                title:_userName+"的"+_logName+"有新的评论"
            };
            $.ajax({
                beforeSend:function(){
                    $(".call_back_success").html("发送中...").show();
                },
                url:apiurl+"/dailyrecords/"+dailyrecord_id+"/comment",
                type:"POST",
                data:data,
                success:function(d){

                    var data = JSON.parse(d);
                    if(data.code==0){
                        $(".call_back_success").html("评论成功").fadeOut(1000,function(){
                            window.location.reload();
                        });
                    }
                }
            })
        } else {
            $(".call_back_success").html("评论内容不能为空").show().fadeOut(1000);
        }
    });


    //$('.comment_box_real').onkeyup = function(e){
    //    var keycode = e.which;
    //    if(keycode==108){
    //        $('.bottom_comment_box').css('bottom','0');
    //    }
    //};

    $('.comment_box_text').bind('focus',function(){
        commitBoxState = true;

        $('.bottom_comment_box').css('bottom',"40vh");
        //$(window).resize();
    });

    //$(window).resize(function() {
    //    var width = $(this).width();
    //    var height = $(this).height();
    //    alert('width'+width+'-height'+height);
    //
    //});

    //var window_height = 0;
    //setInterval(function(){
    //    window_height = $(window).innerHeight();
    //
    //
    //
    //    console.log(height);
    //}, 1000);

    //var

    //$('.comment_box_text').bind('blur',function(){
    ////    //packupKeyboard();
    ////    $('.bottom_comment_box').css('bottom','0');
    ////    //$('.bottom_comment_box').css('bottom','0');
    ////    //$('.comment_box_real').blur();
    //    $('.bottom_comment_box').css('bottom','0');
    //});

    //评论框键盘收起
    //function packupKeyboard() {
    //    if (commitBoxState == true){
    //        commitBoxState = false;
    //        $('.bottom_comment_box').css('bottom','0');
    //        $('.comment_box_real').blur();
    //
    //    }
    //}


    //点击图片查看大图
    $(document).on('click', '.img_img', function () {
        $.watchBigPic($(this));
    });

    //返回
    var quitShare;
    quitShare                    = document.createElement('iframe');
    quitShare.style.display      = 'none';
    document.documentElement.appendChild(quitShare);
    $("#log_back").on('click',function(){
        if(index=="2"){
            quitShare.src = "/quitShare_goBack";
        }else{
            window.location.href="allLog.html?index="+index+"";
            //window.history.back();
            localStorage.removeItem("name");
            localStorage.removeItem("avatar");
            localStorage.removeItem("qyxBindId_log");
            localStorage.removeItem("id");
        }
    });

    function showAvatar(classname){
        $(classname).one("load",function(){
            $(this).show();
            $(this).prev().hide();
        });
    }

});